(function ($) {
    $.fn.yqTextFilebox = function (opts, param) {
        if (typeof opts == 'string') {
            return $.fn.yqTextFilebox.methods[opts](this, param);
        }

        return this.each(function () {
            $this = $(this);
            var opt;
            if ($this.data("yqtype") == "yqTextFilebox") {
                var $uniqueID = $this.attr("ID");
                var opts_ = $.extend({}, options($this));

                destroy($this);
                $this = $("#" + $uniqueID);
                opt = $.extend(opts_, opts);
            }
            else {
                opt = $.extend({}, $.fn.yqTextFilebox.defaults, opts);
                var $uniqueID = $this.attr("ID");
                if ($uniqueID === undefined || $uniqueID === null || $uniqueID == "") {
                    $uniqueID = $.getUniqueID();
                    $this.attr("ID", $uniqueID);
                }
            }

            if (opt.width === undefined && $this.width() > 0) {
                opt.width = $this.width();
            }
            else if (typeof opt.width != "undefined") {
                $this.width(opt.width);
            }

            //变量信息
            $this.data("textfilebox_opt", opt);
            $this.data("yqtype", "yqTextFilebox");

            opt.loadui = false;

            LoadJsCss($this, function () {
                init_edit($this);
            });
        });
    };

    $.fn.yqTextFilebox.defaults = {
        storageType: 2,//1-数据库存储，2-外部存储
        storageName: null,
        accept: "image/*",
        chunk: false,       //分片上传
        directup: false,   //直接上传（选择文件后立即上传）
        data: null,  //{"type":"image/jpeg","size":234,"name":"aaaa.jpge","storage":"aaa","sid":"sid1111"}
        isEdit: true,   //可编辑

        // width: 400, //模态编辑器宽度 格式为 800（数字）
    };

    $.fn.yqTextFilebox.methods = {
        options: function (jq) {
            return options($(jq[0]));
        },
        destroy: function (jq) {
            destroy($(jq[0]));
        },
        resize: function (jq, width) {
            resize($(jq[0]), width);
        },
        clear: function (jq, data) {
            setValue($(jq[0]), null);
        },
        setData: function (jq, data) {
            setData($(jq[0]), data);
        },
        getData: function (jq) {
            return getData($(jq[0]));
        },
        disable: function (jq) {
            isEdit($(jq[0]), false);
        },
        enable: function (jq) {
            isEdit($(jq[0]), true);
        },
    };

    function LoadJsCss($object, callback) {
        var opt = options($object);
        var file = [];
        file.push({ url: "/scripts/crypto/sha256.min.js", type: "js" });
        $.yqLoadJsCss(file, function () {
            callback();
        })
    }

    function options($object) {
        return $object.data("textfilebox_opt");
    }

    function destroy($object) {
        var opt = options($object);

        var $new_obj = $($object.prop("outerHTML"));
        $new_obj.show();
        var id = $object.attr("id");
        $new_obj.removeAttr("id");
        $new_obj.removeClass("textbox-f");
        $new_obj.removeClass("filebox-f");
        $object.before($new_obj);
        $new_obj.attr("id", id);

        $object.filebox("destroy");

        $object.removeData("textfilebox_opt");
        $object.removeData("yqtype");
    }

    function resize($object, width) {
        var opt = options($object);
        if (opt.loadui) {
            if (typeof width != "undefined") {
                opt.width = width;
            }
            $object.filebox("resize", opt.width);
        }
        else {
            setTimeout(function () {
                resize($object, width);
            }, 100);
        }
    }

    function init_edit($object) {
        var opt = options($object);
        $object.filebox({
            accept: opt.accept,
            multiple: false,
            buttonText: '...',
            icons: [{
                iconCls: "icon2-file-blank",
                handler: function (e) {
                    var data = getData($(e.data.target));
                    if (data === null) {
                        return;
                    }

                    if (window.top == window.self) {
                        $.yqFilePopView(data);
                    }
                    else {
                        window.top.$.yqFilePopView(data);
                    }
                }
            }, {
                iconCls: 'yqwin-combo-btn-icon fa fa-times',
                handler: function (e) {
                    setData($(e.data.target), null);
                }
            }],
            onChange: function (newValue, oldValue) {
                console.log(newValue, oldValue);
                onChange($object);
            }
        })

        //var $icon0 = $object.filebox("getIcon", 0);
        //var $icon1 = $object.filebox("getIcon", 1);
        //$icon1.after($icon0);
        opt.loadui = true;

        if (!(opt.data === null)) {
            setData($object, opt.data);
        }
        isEdit($object, opt.isEdit);
    }

    function onChange($object) {
        var files = $object.filebox("files");
        if (files.length == 0) {
            return;
        }
        var opt = options($object);
        var file = files[0];

        if (!opt.directup) {
            setIconClass($object, "icon2-file-" + file.type.split("/")[0]);
            opt.data = null;
            return;
        }


        //chunk
        if (opt.storageType == 2 && opt.chunk) {
            $.yqFileChunkUpload(file, {
                ajaxUrl: '/_file.html',
                // sto_type: opt.storageType,     //1-数据库存储，2-外部存储
                sto_name: opt.storageName,     //外部存储库名
                // 上传完成
                success: function (res) {
                    if (res.error == 0) {
                        setData($object, res.file);
                        $.yqMessager("success", "上传成功。");
                    } else {
                        setData($object, null);
                        $.yqMessager("error", res.info + "[" + res.error + "]");
                    }
                },
            })
        } else {
            $.yqFileUpload(file, {
                ajaxUrl: '/_file.html',
                sto_type: opt.storageType,     //1-数据库存储，2-外部存储
                sto_name: opt.storageName,     //外部存储库名
                // 上传完成
                success: function (res) {
                    if (res.error == 0) {
                        setData($object, res.file);
                        $.yqMessager("success", "上传成功。");
                    } else {
                        setData($object, null);
                        $.yqMessager("error", res.info + "[" + res.error + "]");
                    }
                },
            })
        }
        //console.log(file.type);
    }

    function setIconClass($object, name) {
        var icon = $object.filebox("getIcon", 0);
        var class_ = icon.attr("class").split(" ");
        for (let i = 0; i < class_.length; i++) {
            var cc = class_[i].replace(/(^\s*)|(\s*$)/g, "");
            if (cc.indexOf("fa-search-plus") >= 0) {
                icon.removeClass(cc);
                break;
            }
        }
        icon.addClass(name);
    }

    function setData($object, data) {
        var opt = options($object);
        if (opt.loadui) {
            if (typeof data == "string") {
                data = JSON.parse(data);
            }
            else if (typeof data != "object") {
                data = null;
            }
            opt.data = data;

            $object.filebox("clear");
            if (data === null) {
                $object.filebox("setText", "");
                setIconClass($object, "icon2-file-blank");
            } else {
                $object.filebox("setText", data.name);
                ($object, "icon2-file-" + data.type.split("/")[0]);
            }
        }
        else {
            setTimeout(function () {
                setData($object, data);
            }, 100);
        }
    }

    function getData($object) {
        var opt = options($object);
        var files = $object.filebox("files");
        if (files.length == 0) {
            return opt.data;
        }

        var file = files[0];
        var fileData = {};
        fileData['file'] = file;
        fileData['name'] = file.name;
        fileData['type'] = file.type;
        fileData['size'] = file.size;

        return fileData;
    }

    function isEdit($object, tf) {
        var opt = options($object);
        if (opt.loadui) {
            opt.isEdit = tf;
            if (tf) {
                $object.filebox("enable");
            } else {
                $object.filebox("disable");
            }
        }
        else {
            setTimeout(function () {
                isEdit($object, tf);
            }, 100);
        }
    }

})(jQuery);